package com.backstage.common.uitil;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.SecureRandom;

/**
 * @Project authority
 * @Package com.backstage.common.uitil
 * @Data 2017/7/17上午 9:59.
 * @Aurhor 阮雪峰
 */
public class DES_3 {

    /**
     * 加密
     * @param src
     * @param DES_KEY
     * @return
     */
    public static String encryptBy3DES(String src,String DES_KEY){
        String result=null;
        try {
            SecureRandom secureRandom=new SecureRandom();
            DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes());

            SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede");
            SecretKey key=secretKeyFactory.generateSecret(sedeKeySpec);

            Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key,secureRandom);

            byte[] bytesresult=cipher.doFinal(src.getBytes());
            result=new sun.misc.BASE64Encoder().encode(bytesresult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }

    /**
     * 3重DES解密
     * @param src
     * @param DES_KEY
     * @return
     */
    public static String decryptBy3DES(String src,String DES_KEY){
        String deresult=null;
        try {
            SecureRandom secureRandom=new SecureRandom();
            DESedeKeySpec sedeKeySpec=new DESedeKeySpec(DES_KEY.getBytes());

            SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance("DESede");
            SecretKey key = secretKeyFactory.generateSecret(sedeKeySpec);

            Cipher cipher=Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,key,secureRandom);

            byte[] bytes_result=cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(src));
            deresult=new String(bytes_result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deresult;
    }

    /*public static void main(String[] args) {
        String key = StringUtil.getRandomStr(32);
        System.out.println(key);
        System.out.println(EncryptBy3DES("admin", key));
    }*/
}
